 package rosetti.AR.dossier.premier;

import java.util.ArrayList;
import java.util.List;

import org.openintents.intents.WikitudePOI;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.OverlayItem;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources.NotFoundException;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.method.LinkMovementMethod;
import android.text.util.Linkify;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.TextView;

public class mapPOI extends com.google.android.maps.MapActivity implements LocationListener{
		private MapView mapView;
		private double lat = 0;
		private double lng = 0;
		private LocationManager lm;
	 	private MapController mc;
	    private GeoPoint p;
	    private MyLocationOverlay me=null;
	    private ArrayList<WikitudePOI> list1;
	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.menubar, menu);
	    return true;
	}
	
	/**
	 * Actions appelées lors du clic sur les items du menu
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    // Handle item selection
	    switch (item.getItemId()) {
	        case R.id.about:
	            informations();
	            return true;
	        case R.id.contact:
	            contacter();
	            return true;
	        case R.id.abort:
	            quitter();
	            return true;
	        default:
	            return super.onOptionsItemSelected(item);
	    }
	}
	/**Fonction pour quitter l'activité
	 * 
	 */
	public void quitter(){
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(Messages.getString("AR_premier.1")) //$NON-NLS-1$
				.setCancelable(false)
				.setPositiveButton(Messages.getString("AR_premier.2"), //$NON-NLS-1$
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int id) {

								mapPOI.this.finish();
								
							}
						})
				.setNegativeButton(Messages.getString("AR_premier.3"), //$NON-NLS-1$
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int id) {
								dialog.cancel();
							}
						});
		AlertDialog alert = builder.create();
		alert.show();
		
	}
	
	/** Lance l'application écrire un émail
	 * 
	 */
	private void contacter(){
		final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
		
		emailIntent.setType("plain/text");
		emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{"emmanuel.rosetti@gmail.com"});
		emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,"Remarques table d'orientation");
		emailIntent.putExtra(android.content.Intent.EXTRA_TEXT,"Vos remarques: ");
		
		startActivity(Intent.createChooser(emailIntent, "Envoyer un email..."));
	}
	/**Affiche des informations sur l'application
	 * 
	 */
	public void informations(){
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		
		final SpannableString s= new SpannableString("Application de réalité augmentée développée par Emmanuel Rosetti dans le cadre d'un Projet Informatique de la formation ingénieur 3ème année ENSG.\nCe projet a été commandité par M.Hervé Quinquenel.\nSont utilisés:\n - l' API Google Maps pour la visualisation cartographique\n - l'API Wikitude pour la réalité augmenté\n - le webService GeoNames pour l'altitude des points et la base de données de POIs wikipedia\nPlus d'informations en ligne sur http://code.google.com/p/table-d-orientation\nContact: emmanuel.rosetti@gmail.com\n\u00A9 2012");
		Linkify.addLinks(s, Linkify.ALL);
		builder.setTitle("A propos")
				.setMessage(s)
				.setIcon(R.drawable.ic_launcher)
				.setCancelable(false)
				.setPositiveButton("Ok",
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int id) {
								dialog.cancel();
							}
						});
		AlertDialog alert = builder.create();
		alert.show();
		((TextView)alert.findViewById(android.R.id.message)).setMovementMethod(LinkMovementMethod.getInstance());

	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.mapview);
	    
	    mapView = (MapView) findViewById(R.id.mapview);
	    mapView.setBuiltInZoomControls(true);
	    
	    mc = mapView.getController();
	    
	    list1=AR_premier.listtoutpois;
        lm = (LocationManager) this.getSystemService(LOCATION_SERVICE);
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60000, 50, this);
 
        lat = AR_premier.ici.getLatitude();
        lng = AR_premier.ici.getLongitude();
        p = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));
        int zoom=calculateZoomLevel();
        mc.animateTo(p);
        mc.setCenter(p);
        mc.setZoom(zoom);
        
       
       
        Drawable marker=getResources().getDrawable(R.drawable.marker_wikipedia);
        
        marker.setBounds(0, 0, marker.getIntrinsicWidth(),marker.getIntrinsicHeight());
        
        me=new MyLocationOverlay(this, mapView);
        mapView.getOverlays().add(me);
        mapView.getOverlays().add(new SitesOverlay(marker,list1,AR_premier.range_tot));
        
        
        
	}
	
	@Override
	public void onLocationChanged(Location location)
	{
	   
			int zoom=calculateZoomLevel();
			lat = location.getLatitude();
			lng = location.getLongitude();
			p = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));
            mc.animateTo(p);
            mc.setCenter(p);
            mc.setZoom(zoom);
            
            me=new MyLocationOverlay(this, mapView);
            mapView.getOverlays().add(me);
            mapView.postInvalidate();
            
            try {
				LesPOIs list2= new LesPOIs(location, AR_premier.range_tot, getApplicationContext());
				list2.populate();
				Drawable marker=getResources().getDrawable(R.drawable.marker_wikipedia);
				marker.setBounds(0, 0, marker.getIntrinsicWidth(),marker.getIntrinsicHeight());
				while(list2.size()>0){
				mapView.getOverlays().clear();
				mapView.getOverlays().add(new SitesOverlay(marker,list2,AR_premier.range_tot));
				
				}
			} catch (NotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
           
            
           
	}
 
        //A faire si n�cessaire, gestion du cas quand il y a d�sactivation de l'op�rateur
	@Override
	public void onProviderDisabled(String arg0)
	{
	}
 
        //A faire si n�cessaire, gestion du cas quand il y a r�activation de l'op�rateur
	@Override
	public void onProviderEnabled(String arg0)
	{
	}
 
	@Override
	public void onStatusChanged(String arg0, int arg1, Bundle arg2)
	{
	}
	
	
	
	private int calculateZoomLevel() {
	    DisplayMetrics dm=new DisplayMetrics();
	    getWindowManager().getDefaultDisplay().getMetrics(dm);
		double equatorLength = 6378140*2*Math.PI; // in meters
	    double widthInPixels =dm.widthPixels;
	    double heightInPixels=dm.heightPixels;
	    Log.i("AR_premier","largeur en pixels= "+widthInPixels);
	    double metersPerPixel = equatorLength / 256;
	    int zoomLevel = 1;
	    double min=Math.min(heightInPixels, widthInPixels);
	    while ((metersPerPixel * min) > 2*AR_premier.range_tot*1000) {
	        metersPerPixel /= 2;
	        ++zoomLevel;
	    }
	    Log.i("ADNAN", "zoom level = "+zoomLevel);
	    return zoomLevel;
	}

	 private GeoPoint getPoint(double lat, double lon) {
		    return(new GeoPoint((int)(lat*1000000.0),
		                          (int)(lon*1000000.0)));
		  }
	
	 private class SitesOverlay extends ItemizedOverlay<OverlayItem> {
		    private List<OverlayItem> items=new ArrayList<OverlayItem>();
		    
		    public SitesOverlay(Drawable marker,ArrayList<WikitudePOI> listpois, int range) {
		      super(marker);
		      
		      boundCenterBottom(marker);
		      listpois=list1;
		      
		      for(int i=0;i<list1.size();i++)
		      {
		    	 items.add(new OverlayItem(getPoint(listpois.get(i).getLatitude(),listpois.get(i).getLongitude()),listpois.get(i).getName(),listpois.get(i).getDescription()+"\nLien :"+listpois.get(i).getLink()));
		      }
		      
		      populate();
		    }
		    
		    @Override
		    protected OverlayItem createItem(int i) {
		      return(items.get(i));
		    }
		    
		    @Override
		    protected boolean onTap(int i) {
		     /** Toast.makeText(mapPOI.this,
		                      items.get(i).getSnippet(),
		                      Toast.LENGTH_SHORT).show();
		      */
		      OverlayItem item = items.get(i);
		      final SpannableString s= new SpannableString("Description : " + item.getSnippet());
				Linkify.addLinks(s, Linkify.ALL);
		        AlertDialog alertDialog = new AlertDialog.Builder(mapPOI.this).create();
	                alertDialog.setTitle("Nom : " + item.getTitle());
	                alertDialog.setMessage(s);
	                alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
	                   public void onClick(DialogInterface dialog, int which) {
	                   return;
	                 } });
	                alertDialog.show();
	        	((TextView)alertDialog.findViewById(android.R.id.message)).setMovementMethod(LinkMovementMethod.getInstance());

		      
		      return(true);
		    }
		    
		    @Override
		    public int size() {
		      return(items.size());
		    }
		  }
	 
	   @Override
	   protected void onResume() {
	   	super.onResume();
	   	// when our activity resumes, we want to register for location updates
	   	me.enableMyLocation();
	   }

	   @Override
	   protected void onPause() {
	   	super.onPause();
	   	// when our activity pauses, we want to remove listening for location updates
	   	me.disableMyLocation();
	   	
	   }
	   
	   @Override
		public void onBackPressed() {
			this.finish();

		}
}
